package com.itheima.reggie.exception;

import com.itheima.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

//@ControllerAdvice//表示该类是异常处理器
//@ResponseBody//表示返回数据是JSON串
@RestControllerAdvice/*等于上面俩*/(annotations = {RestController.class, Controller.class})/*annotations属性意思是只收集有指定注解的类中的异常,可写可不写,不写也是收集Controller类中的异常*/
@Slf4j //酸辣粉4斤 日志框架
public class GlobalExceptionHandler {

    //处理SQL唯一字段重复异常
    @ExceptionHandler(value = {SQLIntegrityConstraintViolationException.class/*,2.class,3.class,4.class,...*/})
    public R exceptionHandler1(SQLIntegrityConstraintViolationException e/*异常作为参数*/) {
        log.info("出现了某个唯一字段重复的问题...");
        e.printStackTrace();
        return R.error("对不起,您的用户名重复!");
    }

    @ExceptionHandler(value = {DuplicateKeyException.class/*,2.class,3.class,4.class,...*/})
    public R exceptionHandler2(DuplicateKeyException e/*异常作为参数*/) {
        log.info("出现了某个唯一字段重复的问题...");
        e.printStackTrace();
        return R.error("对不起,您的菜名重复!");
    }


    //兜底接任意异常
    @ExceptionHandler(value = {Exception.class/*,2.class,3.class,4.class,...*/})
    public R exceptionHandler2(Exception e) {
        log.info("出现了某个未预期到的问题...");
        e.printStackTrace();
        return R.error("系统错误,请稍后再试!");
    }
}
